package com.biyao.controller.config.aop;



import com.biyao.schedulingcommon.response.BaseMsg;
import com.biyao.schedulingcommon.response.SuccessMsg;
import com.biyao.controller.config.api.SwaggerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.net.URI;


@Component
@ControllerAdvice
public class ReturnValueConverterAdvice implements ResponseBodyAdvice {

    @Autowired
    private SwaggerConfig swaggerConfig;
    /**
     * 日志记录.
     */
    private Logger logger = LoggerFactory.getLogger(ReturnValueConverterAdvice.class);

    /**
     * @param returnType    returnType
     * @param converterType converterType
     * @return boolean
     */
    @Override
    public final boolean supports(final MethodParameter returnType, final Class converterType) {
        return true;
    }

    /**
     * 在返回前进行封装.
     *
     * @param body                  body
     * @param returnType            returnType
     * @param selectedContentType   selectedContentType
     * @param selectedConverterType selectedConverterType
     * @param request               requestbean
     * @param response              responsebean
     * @return Object
     */
    @Override
    public final Object beforeBodyWrite(final Object body, MethodParameter returnType, MediaType selectedContentType,
                                        Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        URI uri = request.getURI();
        if (swaggerConfig.isSwagger(uri.getPath())) {
            return body;
        }
        if (body instanceof Resource) {
            return body;
        } else if (body instanceof BaseMsg) {
            return body;
        } else if (body instanceof byte[]) {
            return body;
        } else {
            return new SuccessMsg(body);
        }

    }


}
